import 'dart:async'; // 导入Timer类
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_give/repository/api.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';

import '../../common_ui/loading.dart';
import '../../repository/datas/onlineInfo.dart';
import '../../theme.dart';

/// 固件升级页面
class FirmwareupPage extends StatefulWidget {
  final String deviceId;

  // 固件状态
  final bool firmwareswtich;

  // 可升级固件版本
  final String firmwareversion;

  const FirmwareupPage({
    super.key,
    required this.deviceId,
    required this.firmwareswtich,
    required this.firmwareversion,
  });

  @override
  State<StatefulWidget> createState() {
    return _FirmwareupPageState();
  }
}

class _FirmwareupPageState extends State<FirmwareupPage> {
  late String _deviceId;
  late bool _firmwareswtich;
  late String _firmwareversion;
  Timer? _timer; // 定时器对象

  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff), // 设置状态栏颜色
      statusBarIconBrightness: Brightness.dark, // 设置状态栏图标亮度为暗色
    ));

    super.initState();

    _deviceId = widget.deviceId;
    _firmwareswtich = widget.firmwareswtich;
    _firmwareversion = widget.firmwareversion;

    LogUtils.w("设备ID${_deviceId}");
    LogUtils.w("设备开关${_firmwareswtich}");
    LogUtils.w("设备版本${_firmwareversion}");

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff), // 设置状态栏颜色
      statusBarIconBrightness: Brightness.dark, // 设置状态栏图标亮度为暗色
    ));
  }

  @override
  void dispose() {
    _timer?.cancel(); // 页面销毁时关闭定时器
    _timer = null;
    super.dispose();
  }

  void _firmwareup() async {
    OnlineInfo? data = await Api.instance.eqonlineInfo(deviceid: _deviceId);

    LogUtils.w(data?.isOnline);
    if (data?.isOnline == true){


      bool eqswtich = await Api.instance.eqfirmwareup(id: _deviceId,version: _firmwareversion);

     if (eqswtich) {
       Loading.showLoading();
       // 启动定时器，每3秒执行一次
       // _timer = Timer.periodic(Duration(seconds: 3), (timer) {
       //   LogUtils.w("执行定时器");
       //   // 模拟接口调用
       //   _mockApiCall();
       // });
       showToast("固件正在升级，请稍后");
     } else {
       showToast("固件升级失败");
     }

    } else {
      showToast("设备不在线");
    }
  }

  void _mockApiCall() async {
    // 模拟接口调用
    await Future.delayed(Duration(seconds: 15)); // 模拟网络延迟
    LogUtils.w("接口调用成功");
    Loading.dismissAll();
    // 关闭定时器
    _timer?.cancel();
    _timer = null;
    // 退出页面
    // if (mounted) {
    //   Navigator.of(context).pop();
    // }
  }

  Future<bool> _onWillPop() async {
    Loading.dismissAll();
    LogUtils.w("用户点击了返回按钮");
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Color(0xFFF2F3F5),
        appBar: _buildTitleBar(context),
        body: _buildRootBody(context),
      ),
      onWillPop: _onWillPop,
    );
  }

  Widget _buildRootBody(BuildContext context) {
    return Container(
      color: Color(0xFFF2F3F5),
      child: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              _buildbasicsRow(),
              SizedBox(height: 20),
              // 没有升级版本 - 没有不显示
              if (_firmwareswtich) _buildLoginButton(),
              // _buildLoginButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLoginButton() {
    return SizedBox(
      width: 400,
      height: 45,
      child: ElevatedButton(
        onPressed: _firmwareup,
        style: ElevatedButton.styleFrom(
          backgroundColor: SampleThemeConfigure.colorPrimary,
          foregroundColor: SampleThemeConfigure.colorForeground,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '固件升级',
          style: TextStyle(fontSize: 18),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  Widget _buildbasicsRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.0),
        border: Border.all(
          color: Color(0xFFf8f7f7),
          width: 1.0,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            offset: Offset(0, 2),
            blurRadius: 4.0,
            spreadRadius: 0.0,
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 30,
        bottom: 50,
        left: 5,
        right: 5,
      ),
      child: Column(
        children: [
          Image.asset(
            'assets/app_img/firmwareupgrade.png',
            width: 80,
            height: 80,
          ),
          SizedBox(height: 20),
          Container(
            alignment: Alignment.center,
            child: Text(
              _firmwareswtich ?  '点击升级版本' :  '已是最新版本',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SizedBox(height: 2),
          Text(
            '当前版本：${_firmwareversion}',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          _onWillPop();
          Navigator.of(context).pop();
        },
      ),
      automaticallyImplyLeading: false,
      title: Text(
        "固件升级",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }
}
